package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrType;

import java.io.IOException;

public class SROADDATA extends AxdrType {
    private byte[] dataCode = null;
    private OAD soad = null;
    private Data data = null;
    private OAD road = null;
    private Unsigned8 readDelay = null;

    public SROADDATA() {
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    public void setAll(OAD soad, Data data, OAD road, Unsigned8 readDelay) {
        this.soad = soad;
        this.data = data;
        this.road = road;
        this.readDelay = readDelay;
    }

    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.soad = new OAD();
        codeLength += this.soad.decode(input);
        this.data = new Data();
        codeLength += this.data.decode(input);
        this.road = new OAD();
        codeLength += this.road.decode(input);
        this.readDelay = new Unsigned8();
        this.readDelay.setConst();
        codeLength += this.readDelay.decode(input);
        return codeLength;
    }

    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength;
        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (int i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if (this.readDelay != null && this.road != null && this.data != null && this.soad != null) {
                codeLength = 0;
                codeLength += this.readDelay.encode(output);
                codeLength += this.road.encode(output);
                codeLength += this.data.encode(output);
                codeLength += this.soad.encode(output);
            } else {
                throw new RuntimeException("readDelay || road || data || soad is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.toByteArray();
    }

    @Override
    public String toString() {
        if (this.readDelay != null && this.road != null && this.data != null && this.soad != null) {
            return "sequence: {" + "soad: " + this.soad + ", data: " + this.data + ", road: " + this.road + ", delayreadtime: " + this.readDelay + "}";
        } else {
            return "readDelay || road || data || soad is null";
        }
    }
}



